package com.zhan.ielts.web.controller;

import com.zhan.frame.core.utils.EncryptUtile;
import com.zhan.ielts.domain.user.LoginRecord;
import com.zhan.ielts.domain.user.SystemUser;
import com.zhan.ielts.service.user.ILoginRecordService;
import com.zhan.ielts.service.user.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by tlfu on 2017/5/17.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ILoginRecordService loginRecordService;
    @Autowired
    private ISystemUserService systemUserService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "/users/login";
    }

    @RequestMapping(value = "/loginLoad", method = RequestMethod.POST)
    public void login(String username, String password, HttpServletResponse response, HttpServletRequest request) throws Exception {
        SystemUser query = new SystemUser();
        query.setUserName(username);
        query.setPassword(EncryptUtile.encrypt(password));
        SystemUser result = systemUserService.queryOne(query);
        if (result != null) {
            request.getSession().setAttribute("username", username);
            String root = "http://" + request.getHeader("Host");
            if (!StringUtils.isEmpty(request.getContextPath())) {
                root = root + request.getContextPath();
            }
            LoginRecord record = new LoginRecord();
            record.setUserName(username);
            record.setLoginTime(new Date());
            loginRecordService.insert(record);
            String url = (String)request.getSession().getAttribute("url");
            if (request.getSession().getAttribute("url") != null) {
                response.sendRedirect(url);
            }else{
                response.sendRedirect(root);
            }
        } else {
            response.getWriter().write("username or password is error!");
        }
    }
}
